<!-- src/components/ParamMapping.vue -->
<template>
  <div class="param-mapping">
    <!-- 统计信息 -->
    <div v-if="mappingList.length > 0" class="stats-info">
      <el-alert
        :title="`总计 ${stats.total} 个参数，其中必填 ${stats.required} 个，选填 ${stats.optional} 个`"
        type="info"
        :closable="false"
        show-icon
      >
        <template slot="title">
          <span>参数统计：</span>
          <el-tag type="info" size="small">总计: {{ stats.total }}</el-tag>
          <el-tag type="danger" size="small">必填: {{ stats.required }}</el-tag>
          <el-tag type="success" size="small">选填: {{ stats.optional }}</el-tag>
          <el-tag size="small">必填率: {{ stats.requiredPercentage }}%</el-tag>
        </template>
      </el-alert>
    </div>

    <!-- 对照表展示 -->
    <div v-if="mappingList.length > 0" class="mapping-table">
      <el-table 
        :data="mappingList" 
        stripe 
        style="width: 100%"
        :default-sort="{ prop: 'required', order: 'descending' }"
        height="400"
      >
        <el-table-column prop="paramName" label="参数名称" min-width="200" fixed="left"></el-table-column>
        <el-table-column prop="paramCode" label="Code编码" min-width="200"></el-table-column>
        <el-table-column prop="required" label="是否必填" width="100" align="center">
          <template slot-scope="scope">
            <el-tag 
              :type="scope.row.required ? 'danger' : 'success'" 
              size="small"
            >
              {{ scope.row.required ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="templateVariable" label="模板变量" min-width="200">
          <template slot-scope="scope">
            <el-tooltip 
              effect="dark" 
              :content="`点击复制: ${scope.row.templateVariable}`" 
              placement="top"
            >
              <el-tag 
                type="success" 
                size="small"
                class="copyable-tag"
                @click="copyToClipboard(scope.row.paramCode)"
              >
                {{ scope.row.templateVariable }}
              </el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="copyToClipboard(scope.row.paramCode)"
            >
              复制Code
            </el-button>
            <el-button 
              v-if="scope.row.required"
              type="text" 
              size="small"
              @click="showRequiredInfo(scope.row)"
            >
              必填规则
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty description="暂无参数对照数据">
        <el-button type="primary" @click="generateMapping">生成对照表</el-button>
      </el-empty>
    </div>

    <!-- 必填规则详情 -->
    <el-dialog 
      title="必填参数详情" 
      :visible.sync="requiredInfoVisible" 
      width="500px"
    >
      <div v-if="currentRequiredParam" class="required-info">
        <p><strong>参数名称：</strong>{{ currentRequiredParam.paramName }}</p>
        <p><strong>Code编码：</strong>{{ currentRequiredParam.paramCode }}</p>
        <p><strong>模板变量：</strong><el-tag type="success">{{ currentRequiredParam.templateVariable }}</el-tag></p>
        <p><strong>必填提示：</strong>{{ currentRequiredParam.requiredMsg || '此字段为必填项' }}</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="requiredInfoVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ParamParser from '@/utils/paramParser'

export default {
  name: 'ParamMapping',
  props: {
    projectConfig: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      mappingList: [],
      requiredInfoVisible: false,
      currentRequiredParam: null,
      stats: {
        total: 0,
        required: 0,
        optional: 0,
        requiredPercentage: 0
      }
    }
  },
  mounted() {
    // 组件挂载后自动生成对照表
    this.generateMapping()
  },
  methods: {
    /**
     * 生成参数对照表
     */
    generateMapping() {
      try {
        this.mappingList = ParamParser.generateParamMapping(this.projectConfig)
        this.stats = ParamParser.getRequiredStats(this.projectConfig)
        this.$message.success(`成功生成 ${this.mappingList.length} 个参数对照`)
      } catch (error) {
        this.$message.error('生成对照表失败：' + error.message)
        console.error('生成对照表错误：', error)
      }
    },

    /**
     * 导出对照表 - 供父组件调用
     */
    exportMapping(format) {
      try {
        ParamParser.exportMapping(this.projectConfig, format)
        this.$message.success('导出成功')
      } catch (error) {
        this.$message.error('导出失败：' + error.message)
      }
    },

    /**
     * 复制到剪贴板
     */
    copyToClipboard(text) {
      const textarea = document.createElement('textarea')
      textarea.value =  '${' + text + '}' 
      document.body.appendChild(textarea)
      textarea.select()
      try {
        document.execCommand('copy')
        this.$message.success('复制成功: ' + text)
      } catch (err) {
        this.$message.error('复制失败')
      }
      document.body.removeChild(textarea)
    },

    /**
     * 显示必填参数详情
     */
    showRequiredInfo(param) {
      this.currentRequiredParam = param
      this.requiredInfoVisible = true
    }
  },
  watch: {
    // 监听项目配置变化，自动重新生成
    // projectConfig: {
    //   handler(newVal) {
    //     console.log('projectConfig:', newVal)
    //     if (newVal && newVal.paramGroups) {
    //       this.generateMapping()
    //     }
    //   },
    //   immediate: true,
    //   deep: true
    // }
  }
}
</script>

<style scoped>
.param-mapping {
  padding: 0;
}

.stats-info {
  margin-bottom: 15px;
}

.stats-info .el-alert__title {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.mapping-table {
  margin-top: 10px;
}

.empty-state {
  margin: 50px 0;
  text-align: center;
}

.required-info p {
  margin: 10px 0;
  line-height: 1.6;
}

.copyable-tag {
  cursor: pointer;
  user-select: none;
}

.copyable-tag:hover {
  opacity: 0.8;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .el-tag) {
  margin: 2px;
}
</style>